﻿using App.Desk.CameraHelper.HK;
using App.Desk.Extend;
using App.Desk.Pro.Monitors;
using App.Desk.Pro.SamplingData;
using App.Model;
using App.Untiys;
using Newtonsoft.Json.Linq;
using S7.Net;
using SqlSugar;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using Win.Dal;

namespace App.Desk.Pro.Sampling
{
    /// <summary>
    /// 火车采样中控台
    /// </summary>
    public partial class FrmTrain : UIPage
    {
        #region 全局变量
        /// <summary>
        /// 电机状态监听窗体
        /// </summary>
        FrmElectricalState Q_FrmElectricalState;

        /// <summary>
        /// 限位状态监听窗体
        /// </summary>
        FrmProtectState Q_FrmProtectState;

        /// <summary>
        /// 计划窗体
        /// </summary>
        FrmPlansList Q_FrmPlansList;

        /// <summary>
        /// 上传三大项开关
        /// </summary>
        bool Q_IsUploadSdxStart = false;

        /// <summary>
        /// 三大项上传线程
        /// </summary>

        Thread Q_ThUploadSdx = null;

        /// <summary>
        /// 清除历史抓拍照片线程
        /// </summary>

        Thread Q_ThClearHistoryPicture = null;

        #endregion

        public FrmTrain()
        {
            InitializeComponent();
            Q_FrmElectricalState = new FrmElectricalState();
        }

        private void FrmTrain_Load(object sender, EventArgs e)
        {
            GlobalSampling.Q_HKCameraHelper = null;
            SetSysConfig();
            SetPageConfig();
            SetStartCamera();
            btnStart.Text = txtSamplineType.SelectedText;
            Q_IsUploadSdxStart = true;
            Q_ThUploadSdx = new Thread(new ThreadStart(DoUploadDataToSdxThread)) { IsBackground = true };
            Q_ThUploadSdx.Start();
            Q_ThClearHistoryPicture = new Thread(new ThreadStart(DoClearHistoryPicture)) { IsBackground = true };
            Q_ThClearHistoryPicture.Start();
            InitRead();
        }

        public void InitRead()
        {
            try
            {
                txtPoint.Value = SamplingPLCHelper.Instance.DoRead(144).ToIntEx();
                txtZyycTime.Value = SamplingPLCHelper.Instance.DoRead(146).ToIntEx();
                txtSfsj.Value = SamplingPLCHelper.Instance.DoRead(276).ToIntEx();
            }
            catch
            {

            }
        }

        #region  清除历史照片和日志文件
        /// <summary>
        /// 清空30天之前的图片文件
        /// </summary>
        public void DoClearHistoryPicture()
        {
            DeleteHistoryLogFiles(Environment.CurrentDirectory.ToString() + "\\log\\");
            string picDirectory = Environment.CurrentDirectory.ToString() + "\\Screenshot\\";
            var dirs = Directory.GetDirectories(picDirectory);
            dirs.ForEach(res =>
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(res);
                var creationTime = directoryInfo.CreationTime;
                var dirName = directoryInfo.Name;
                if (dirName.ToIntEx() < DateTime.Now.AddDays(-30).ToString("yyyyMMdd").ToIntEx())
                    DeleteFilesAndSubdirectories(directoryInfo.FullName);
                if (creationTime < DateTime.Now.AddDays(-30))
                    DeleteFilesAndSubdirectories(directoryInfo.FullName);
            });
        }

        /// <summary>
        /// 删除该目录下的所有文件和子目录
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteFilesAndSubdirectories(string path)
        {
            try
            {
                // 获取指定路径下所有的文件，包括子文件夹内的文件
                foreach (string filePath in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
                {
                    File.Delete(filePath); // 删除文件
                }
                // 获取指定路径下所有的子目录，包括子文件夹内的子目录
                foreach (string directoryPath in Directory.GetDirectories(path, "*", SearchOption.AllDirectories))
                {
                    Directory.Delete(directoryPath); // 删除空的子目录
                }
                Directory.Delete(path); // 删除自身
            }
            catch
            {

            }
            finally
            {

            }
        }

        /// <summary>
        /// 删除历史数据
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteHistoryLogFiles(string path)
        {
            try
            {
                // 获取指定路径下所有的文件，包括子文件夹内的文件
                foreach (string filePath in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
                {
                    FileInfo fileInfo = new FileInfo(filePath);
                    if (fileInfo != null)
                        if (fileInfo.CreationTime < DateTime.Now.AddDays(-30))
                            File.Delete(filePath); // 删除文件
                }
            }
            catch
            {

            }
            finally
            {

            }
        }

        #endregion

        /// <summary>
        /// 连接登录摄像头
        /// </summary>
        private void SetStartCamera()
        {
            string IPCameraAddress = Config.IPCameraAddress;
            string HKWSLogonUser = Config.HKWSLogonUser;
            string HKWSLogonPass = Config.HKWSLogonPass;
            new Thread(delegate (object obj)
            {
                try
                {
                    string msg = "";
                    string dVRIPAddress = obj.ToString();
                    GlobalSampling.Q_HKCameraHelper = new HK_IPCamera(dVRIPAddress, 8000, HKWSLogonUser, HKWSLogonPass, out msg);
                    if (msg == "正常")
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"摄像头连接信息：{msg}");
                    else
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"摄像头连接信息：{msg}");
                }
                catch (Exception ex)
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"摄像头异常：{ex.Message}");
                    LogHelper.DoWriteLogType(Untiys.LogType.Error, $"摄像头异常：{ex.Message}");
                }
            })
            {
                IsBackground = true
            }.Start(IPCameraAddress);
        }

        /// <summary>
        /// 初始化配置文件
        /// </summary>
        public void SetSysConfig()
        {
            if (SamplingPLCHelper.Instance.DoStart(Config.SampingerName, Config.SampingerIp, 102, 0, 200))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"PLC连接成功");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"PLC连接失败");
            SamplingPLCHelper.Instance.PlcDataReadOut += OnPlcDataReadOut;
        }

        /// <summary>
        /// 初始化页面模块
        /// </summary>
        public void SetPageConfig()
        {
            Q_FrmElectricalState = new FrmElectricalState();
            Q_FrmProtectState = new FrmProtectState();
            Q_FrmPlansList = new FrmPlansList();
            AddTabPage(Q_FrmElectricalState, panlElectricalState);
            AddTabPage(Q_FrmProtectState, panlProtectState);
            AddTabPage(new FrmRunData(), panlRunData);
            AddTabPage(new FrmRunState(), panlRunState);
            AddTabPage(Q_FrmPlansList, panlPlans);
        }

        private void AddTabPage(Form frm, UIPanel page)
        {
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.TopLevel = false;
            frm.Dock = DockStyle.Fill;
            frm.WindowState = FormWindowState.Maximized; //如果windowState设置为最大化，添加到tabPage中时，winform不会显示出来
            frm.Dock = DockStyle.Fill;
            var isHave = false;

            foreach (var item in page.Controls)
            {
                if (item == frm)
                    isHave = true;
            }
            if (!isHave)
                page.Controls.Add(frm);
            frm.Show();
        }

        #region 上传数据到三大项 定时

        /// <summary>
        /// 上传数据到三大项
        /// </summary>
        public void DoUploadDataToSdxThread()
        {
            FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"定时上传线程启动");
            Thread.Sleep(1000 * 5);
            while (Q_IsUploadSdxStart)
            {
                DoUploadDataToSdx(0, false);
                Thread.Sleep(1000 * 60 * 3); //*分钟执行一次
            }
        }

        public void DoUploadDataToSdx(int samplingId = 0, bool isThread = false)
        {
            try
            {
                var data = Config.AleradyUploadUrls(samplingId);
                List<string> retList = new List<string>();
                Thread thread;
                if (data.IsNotNull())
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"检测到{data.Count}条待上传数据");
                data.ForEach(res =>
                {
                    if (!isThread)
                        DefaultUpload(res);
                    else
                    {
                        //线程方式上传
                        thread = new Thread(new ParameterizedThreadStart(ThreadUpload));
                        thread.Start(res);
                    }
                    Thread.Sleep(1000 * 5);//*秒传一条
                });
                if (data.IsNotNull() && !isThread)//定时上传模式，并且上传了数据的情况下才会刷新界面
                    if (Q_FrmPlansList != null) Q_FrmPlansList.ThreadQuery();//刷新界面
                if (data.IsNotNull())
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"{data.Count}条数据上传完成");

            }
            catch (Exception ex)
            {
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"上传异常{ex.Message}");
                LogHelper.DoWriteLogType(LogType.Upload, $"上传异常{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 普通上传
        /// </summary>
        /// <param name="urlStr"></param>
        public void DefaultUpload(object urlStr)
        {
            var result = DataTranf.GetHTML(urlStr.ToString());
            if (result.Contains("OK"))
            {
                var _rSamplingId = result.Replace("OK", "").ToIntEx();
                if (ProSamplingServices.SetUploaded(_rSamplingId))
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"编号：{_rSamplingId}上传成功");
                    LogHelper.DoWriteLogType(LogType.Upload, $"编号：{_rSamplingId}上传成功");
                }
            }
        }

        /// <summary>
        /// 线程模式 单条模式
        /// </summary>
        /// <param name="urlStr"></param>
        public void ThreadUpload(object urlStr)
        {
            var result = DataTranf.GetHTML(urlStr.ToString());
            if (result.Contains("OK"))
            {
                var _rSamplingId = result.Replace("OK", "").ToIntEx();
                if (ProSamplingServices.SetUploaded(_rSamplingId))
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"编号：{_rSamplingId}上传成功");
                    LogHelper.DoWriteLogType(LogType.Sampling, $"编号：{_rSamplingId}上传成功");
                    if (Q_FrmPlansList != null) Q_FrmPlansList.ThreadQuery();//刷新界面
                }
            }
        }

        #endregion

        /// <summary>
        /// PLC监听线程 
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnPlcDataReadOut(object send, ActiveReadEventArgs e)
        {

            //此处监听PLC回调传参，进行采样逻辑处理

            //在线程中 刷新样桶数据
            //frmPail.BindListForThread();

            ////往界面写日志以及后台
            //FormHelper.RicMsgShow(txtFormLog, Unitys.Enum.MsgType.Information, "！！！");

            ////往后台单独写日志
            //LogHelper.DoWriteLogTypeSubitem(LogType.Program, LogSubitem.Log, "！！！");
            short[] _arrReads = (short[])e.E_ReadValue;
            var V20 = DataConvert.Ushort2Binary((int)(_arrReads[20 / 2]));
            var V24 = DataConvert.Ushort2Binary((int)(_arrReads[24 / 2]));
            var V30 = DataConvert.Ushort2Binary((int)(_arrReads[30 / 2]));
            var V40 = DataConvert.Ushort2Binary((int)(_arrReads[40 / 2]));
            UIHelper.SetLabelTextControl(txtPLCStatus, $"{V40[10]}:" + DateTime.Now.ToString("ss"));
            GlobalSampling.SamplingIsReady = V20[3] == 1;//采样是否准备好
            //GlobalSampling.AllowContinue = V24[2] == 1;//是否可以继续下一车
            GlobalSampling.AllowSampling = V40[10] == 1;//   V40[10] == 1;  V40[13] == 1//允许采样 第四节往后需要辅以此信号
            GlobalSampling.BAndSCarToTarget = V20[5] == 1;//大小车去目标点中

            if (!GlobalSampling.SamplingAutoBegining)
                return;

            if (!GlobalSampling.IsSampling)
            {
                GlobalSampling.ResetIsGetStatus();
                //获取最新的需要采样
                GlobalSampling.CurrentSamplingData = ProSamplingServices.GetCurrentMinIndexData(GlobalSampling.LocalBatchId);
                GlobalSampling.IsSampling = true;
                if (GlobalSampling.CurrentSamplingData == null)
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"没有获取到采样计划/计划执行完毕");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"没有获取到采样计划/计划执行完毕");
                    return;
                }
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"---------------------------------------------");
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"第{GlobalSampling.CurrentSamplingData.TrainIndex}节采样开始");
                LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"开始执行第{GlobalSampling.CurrentSamplingData.TrainIndex}节车厢采样");
                //var currentPailNo = SysPailServices.GetPailIdForSampling(GlobalSampling.CurrentSamplingData.SimplingPoint);
                var currentPailNo = SysPailServices.GetPailIndexForSampling(GlobalSampling.CurrentSamplingData.SimplingPoint, GlobalSampling.CurrentSamplingData.SupplierCode);

                GlobalSampling.CurrentSamplingData.PailNo = currentPailNo;
                if (currentPailNo <= 0)
                {
                    /*当前样桶已满，需要出桶*/
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"已无可用采样桶，请先清理样桶");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"已无可用采样桶，请先清理样桶");
                    Thread.Sleep(60 * 1000);//一分钟以后，恢复采样过程
                    return;
                }
                else
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"当前放样桶号：{currentPailNo}#");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"当前放样桶号：{currentPailNo}#");
                    if (ProSamplingServices.SetBucketNo(GlobalSampling.CurrentSamplingData.SamplingId, currentPailNo.ToString()))
                    {
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"保存当前放样桶号：{currentPailNo}#");
                        LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"保存当前放样桶号：{currentPailNo}#");
                    }
                }
                List<ProSamplingPos> posList = new List<ProSamplingPos>();
                List<string> blockList = new List<string>();
                if (!ReleaseSamplingPos(out posList, out blockList))
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"采样坐标生成失败E1");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"采样坐标生成失败E1");
                    return;
                }
                if (posList.IsNotNull())
                {
                    //设置采样开始时间
                    ProSamplingServices.SetStartTime(GlobalSampling.CurrentSamplingData.SamplingId);
                    if (ProSamplingServices.SaveSamplingPos(GlobalSampling.CurrentSamplingData.SamplingId, posList))
                    {
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"保存坐标信息成功");
                        LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"保存坐标信息成功");
                    }
                    if (ProSamplingServices.UpdateSamplingPos(GlobalSampling.CurrentSamplingData.SamplingId, posList))
                    {
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"更新实际坐标信息成功");
                        LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"更新实际坐标信息成功");
                    }
                }
                else
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"采样坐标生成失败E2");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"采样坐标生成失败E2");
                    return;
                }
                GlobalSampling.CurrentSamplingData.PosList = posList;
                GlobalSampling.CurrentSamplingData.BlockList = blockList;
                //执行PLC命令
                SamplingPLCOperation();
            }

            //检测到采样完成信号
            if (V24[0] == 1 && !GlobalSampling.IsGetComplete)
            {
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"采样完成");
                GlobalSampling.IsGetComplete = true;
                #region 随机一个重量

                //Random ran_int = new Random(DateTime.Now.Millisecond);
                //Random ran_float = new Random(DateTime.Now.Millisecond);
                //int i = ran_int.Next(0, 2);
                //double f = 0;
                //if (i == 0)
                //{
                //    f = Math.Round(ran_float.NextDouble(), 1);
                //    if (f < 0.5)
                //        f += 0.5;
                //}
                //else
                //{
                //    f = Math.Round(ran_float.NextDouble());
                //    if (f >= 0.5)
                //        f = f - 0.5;
                //}
                //var weight = (decimal)i + (decimal)f;
                //if (weight < 1m || weight > 3m)
                //{
                //    Random random = new Random();
                //    decimal d = random.Next(11, 25);
                //    weight = d / 10m;
                //}
                var weight = new Random(DateTime.Now.Millisecond).ToNextDouble(0.8, 1.5);
                GlobalSampling.CurrentSamplingData.SimplingWeight = weight.ToString("0.0");

                #endregion
                if (ProSamplingServices.SetSuccessed(GlobalSampling.CurrentSamplingData.SamplingId, Config.CurrentUser.ChName, GlobalSampling.CurrentSamplingData.SimplingWeight))
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"设置本地采样完成");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"设置本地采样完成");
                    //更新样桶
                    if (SysPailServices.SetPailValue(GlobalSampling.CurrentSamplingData.PailNo, GlobalSampling.CurrentSamplingData.SimplingPoint, GlobalSampling.CurrentSamplingData.SupplierCode))
                    {
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"样桶信息更新");
                        LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"样桶信息更新");
                    }
                    DoUploadDataToSdx(GlobalSampling.CurrentSamplingData.SamplingId, true);
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"第{GlobalSampling.CurrentSamplingData.TrainIndex}节采样结束 ");
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"---------------------------------------------");

                    if (Q_FrmPlansList != null) Q_FrmPlansList.ThreadQuery();//刷新界面

                }
            }
            //检测到截图信号
            if (V24[1] == 1 && !GlobalSampling.IsGetScreenshot)
            {
                GlobalSampling.IsGetScreenshot = true;
                var message = GlobalSampling.Screenshot(GlobalSampling.CurrentSamplingData);
                if (message != "OK")
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, message);
            }

            if (V20[9] == 1)//采样头上升 获取/计算子样重量
            {
            }
            if (!GlobalSampling.AllowContinue)
            {
                GlobalSampling.AllowContinue = V24[2] == 1;
                if (GlobalSampling.AllowContinue) //下一节触发
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"触发下一节V24[2]={V24[2]}");
                }
            }
            if (GlobalSampling.AllowContinue)
            {
                var nextTrainIndex = GlobalSampling.CurrentSamplingData.TrainIndex + 1;
                if (nextTrainIndex <= 3)
                {
                    GlobalSampling.IsSampling = false;
                    GlobalSampling.AllowContinue = false;
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"下一节 开始");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"下一节 开始");
                }
                if (nextTrainIndex > 3)
                {
                    if (GlobalSampling.AllowSampling)
                    {
                        GlobalSampling.IsSampling = false;//第4节开始需要拿到允许采样状态 V40[10] == 1
                        GlobalSampling.AllowContinue = false;
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"下一节 开始");
                        LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"下一节 开始");
                    }
                    if (GlobalSampling.AllowContinue)
                        FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"等待 V40[10]:{V40[10]}");
                }
            }
        }

        /// <summary>
        /// 将服务器的坐标 加上保护值 
        /// </summary>
        /// <param name="lastPosList"></param>
        /// <param name="blockStr"></param>
        /// <returns></returns>
        public bool ReleaseSamplingPos(out List<ProSamplingPos> lastPosList, out List<string> blockList)
        {
            lastPosList = new List<ProSamplingPos>();
            blockList = new List<string>();
            string simplingLocation = GlobalSampling.CurrentSamplingData.SimplingLocation;
            string[] arraySimplingLocation = simplingLocation.ToSplitArrayEx('|').ToArray();
            for (int i = 0; i < arraySimplingLocation.Length; i++)
            {
                string[] tempPos = arraySimplingLocation[i].ToSplitArrayEx(',').ToArray();
                ProSamplingPos samplingPos = new ProSamplingPos();
                int posX = int.Parse(tempPos[0]);
                int posY = int.Parse(tempPos[1]);
                samplingPos.RowNO = (((posX / 208 > 5) ? 5 : (posX / 208)) + 1);
                samplingPos.ColNO = (((posY / 29 > 2) ? 2 : (posY / 29)) + 1);
                int blockNO = ((posX / 208 > 5) ? 5 : (posX / 208)) * 3 + ((posY / 29 > 2) ? 2 : (posY / 29)) + 1;
                samplingPos.BlockNO = blockNO;
                samplingPos.X = ((int)(posX * 172 * 1.0m / 1250m) + 8);
                samplingPos.Y = ((int)(posY * 60 * 1.0m / 289m) + 132);
                samplingPos.Z = (157);

                #region 大小车保护

                //下位机 保护坐标
                //小车 130-194  大车0-1000
                if (samplingPos.X <= 0)
                    samplingPos.X = 1;
                if (samplingPos.X >= 1000)
                    samplingPos.X = 999;

                if (samplingPos.Y <= 130)
                    samplingPos.Y = 131;
                if (samplingPos.Y >= 194)
                    samplingPos.Y = 193;

                #endregion

                samplingPos.SamplingId = GlobalSampling.CurrentSamplingData.SamplingId;
                blockList.Add(samplingPos.BlockNO.ToString());
                lastPosList.Add(samplingPos);
            }
            return true;
        }

        /// <summary>
        /// 采样命令下发操作
        /// </summary>
        public bool SamplingPLCOperation()
        {
            try
            {
                var samplingKey = GlobalSampling.SamplingKey;
                if (GlobalSampling.CurrentSamplingData.TrainIndex == 1)
                {
                    if (GlobalSampling.SamplingKey == 120)
                        samplingKey = 121;//洗样
                    if (GlobalSampling.SamplingKey == 101)
                        samplingKey = 111;//洗样
                    if (GlobalSampling.SamplingKey == 102)
                        samplingKey = 112;//洗样
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"洗样{samplingKey}");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"洗样{samplingKey}");
                }
                else
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"非洗样{samplingKey}");
                    LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"非洗样{samplingKey}");
                }

                //允许牵车先决条件 禁止牵车 VW278==100 /允许牵车 VW278==0  (前两节车厢采样完不允许牵车)
                if (GlobalSampling.CurrentSamplingData.TrainIndex <= 2)
                    SamplingPLCHelper.Instance.DoWrite(278, (short)100);
                else
                    SamplingPLCHelper.Instance.DoWrite(278, (short)0);
                //前三节采样命令
                if (GlobalSampling.CurrentSamplingData.TrainIndex <= 3)
                    SamplingPLCHelper.Instance.DoWrite(280, (short)100);
                else if (GlobalSampling.CurrentSamplingData.TrainIndex == 4)
                    SamplingPLCHelper.Instance.DoWrite(282, (short)100);
                else
                {
                    //第五节往后的采样命令
                    SamplingPLCHelper.Instance.DoWrite(282, (short)0);
                    SamplingPLCHelper.Instance.DoWrite(280, (short)0);
                }

                SamplingPLCHelper.Instance.DoWrite(150, (short)samplingKey);
                SamplingPLCHelper.Instance.DoWrite(152, (short)GlobalSampling.CurrentSamplingData.SimplingPoint);
                SamplingPLCHelper.Instance.DoWrite(154, (short)GlobalSampling.CurrentSamplingData.PailNo);
                SamplingPLCHelper.Instance.DoWrite(156, (short)0);
                SamplingPLCHelper.Instance.DoWrite(158, (short)0);
                SamplingPLCHelper.Instance.DoWrite(160, (short)0);
                SamplingPLCHelper.Instance.DoWrite(162, (short)0);

                for (int i = 0; i < GlobalSampling.CurrentSamplingData.PosList.Count; i++)
                {
                    var item = GlobalSampling.CurrentSamplingData.PosList[i];
                    SamplingPLCHelper.Instance.DoWrite(164 + 6 * i, (short)item.X);
                    SamplingPLCHelper.Instance.DoWrite(166 + 6 * i, (short)item.Y);
                    SamplingPLCHelper.Instance.DoWrite(168 + 6 * i, (short)item.Z);
                }
                //FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"坐标{GlobalSampling.CurrentSamplingData.PosList.ToJsonEx()}");
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"采样命令下达成功 车厢位置{GlobalSampling.CurrentSamplingData.TrainIndex}");
                LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"采样命令下达成功 车厢位置{GlobalSampling.CurrentSamplingData.TrainIndex}");
                return true;
            }
            catch (Exception ex)
            {
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"采样命令下达失败：{ex.StackTrace}");
                LogHelper.DoWriteLogType(Untiys.LogType.Sampling, $"采样命令下达失败：{ex.StackTrace}");
                return false;
            }
        }

        private void btnSetPoint_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(144, (short)txtPoint.Value))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"设定放样点数为：{txtPoint.Value}");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"设定放样点数失败");
        }

        private void btnSetSfTime_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(146, (short)txtZyycTime.Value))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"设定制样延迟时间为：{txtZyycTime.Value}秒");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"设定制样延迟时间失败");
        }

        public void SetPlanControlButtonEnabled(bool eabled)
        {
            for (int i = 0; i < Q_FrmPlansList.GetAllControls().Count; i++)
            {
                var control = Q_FrmPlansList.GetAllControls()[i];
                if (control is UIButton)
                    if (!((UIButton)control).Text.Contains("强制"))
                        ((UIButton)control).Enabled = eabled;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            GlobalSampling.SamplingAutoBegining = !GlobalSampling.SamplingAutoBegining;
            if (GlobalSampling.SamplingAutoBegining)
            {
                GlobalSampling.ResetStatus();
                //#region 模拟 
                //GlobalSampling.SamplingIsReady = true;
                //#endregion

                if (!GlobalSampling.SamplingIsReady)
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"采样机当前未处于自动准备好状态，无法启动自动");
                    GlobalSampling.SamplingAutoBegining = false;
                    return;
                }
                GlobalSampling.LocalBatchId = Q_FrmPlansList.CurrentLocalBatch;
                if (ProSamplingServices.GetCurrentMinIndexData(GlobalSampling.LocalBatchId) == null)
                {
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"（{GlobalSampling.LocalBatchId}）当前没有可执行计划");
                    GlobalSampling.SamplingAutoBegining = false;
                    return;
                }
                GlobalSampling.SamplingAutoBegining = true;
                SetPlanControlButtonEnabled(false);
                txtSamplineType.Enabled = false;
            }

            btnStart.Text = GlobalSampling.SamplingAutoBegining ? "停止采样" : txtSamplineType.SelectedText;
            if (GlobalSampling.SamplingAutoBegining)
                btnStart.Style = UIStyle.LayuiOrange;
            else
                btnStart.Style = UIStyle.Green;
            if (!GlobalSampling.SamplingAutoBegining)//点击停止采样 设备复位，故障复位
            {
                SetPlanControlButtonEnabled(true);
                txtSamplineType.Enabled = true;
                if (SamplingPLCHelper.Instance.DoWrite(150, 300))
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送设备复位命令成功");
                else
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送设备复位命令失败，请手动");

                if (SamplingPLCHelper.Instance.DoWrite(150, 200))
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送故障复位命令成功");
                else
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送故障复位命令失败，请手动");
            }
        }

        /// <summary>
        /// 放大缩小主窗体 调整窗体控件大小自适应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSamplingA_Resize(object sender, EventArgs e)
        {
            AddTabPage(Q_FrmElectricalState, panlElectricalState);
            AddTabPage(Q_FrmProtectState, panlProtectState);
            //if (isFirstLoad > 0)
            //{
            //    var panls = this.GetAllControls().Where(m => m is TabPage).ToList();
            //    panls.ForEach(item =>
            //    {
            //        var frm = item.GetAllControls().Where(m => m is Form).FirstOrDefault();
            //        if (frm != null)
            //        {
            //            var tempForm = (UIPage)frm;
            //            tempForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            //            tempForm.TopLevel = false;
            //            tempForm.Dock = DockStyle.Fill;
            //            tempForm.WindowState = FormWindowState.Maximized; //如果windowState设置为最大化，添加到tabPage中时，winform不会显示出来
            //            tempForm.Dock = DockStyle.Fill;
            //            //pane.Controls.Add(frm);
            //            tempForm.Refresh();
            //        }
            //    });
            //}
            //isFirstLoad++;
        }

        /// <summary>
        /// 暂停/恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPause_Click(object sender, EventArgs e)
        {
            if (this.btnPause.Text == "暂停")
            {
                if (SamplingPLCHelper.Instance.DoWrite(272, 100))
                {
                    this.btnPause.Text = "恢复";
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送设备暂停命令成功");
                }
                else
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送设备暂停命令失败，请手动");
            }
            else
            {
                if (SamplingPLCHelper.Instance.DoWrite(272, 0))
                {
                    this.btnPause.Text = "暂停";
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送设备恢复运行命令成功");
                }
                else
                    FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送设备恢复运行命令失败，请手动");
            }
        }

        private void btnResetDevice_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(150, 300))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送设备复位命令成功");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送设备复位命令失败，请手动");
        }

        private void btnResetFault_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(150, 200))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送故障复位命令成功");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送故障复位命令失败，请手动");
        }

        private void btnGoSafeLocation_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(150, 400))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送回安全位置命令成功");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送回安全位置命令失败，请手动");
        }

        private void btnBackBucket_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(150, 500))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"发送回取桶位置命令成功");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"发送回取桶位置命令失败，请手动");
        }

        private void txtSamplineType_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnStart.Text = txtSamplineType.SelectedText;
            if (txtSamplineType.SelectedText.Contains("向左"))
                GlobalSampling.SamplingKey = 102;
            else if (txtSamplineType.SelectedText.Contains("向左"))
                GlobalSampling.SamplingKey = 101;
            else
                GlobalSampling.SamplingKey = 120;
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            var data = ProSamplingServices.GetCurrentMinIndexData(Q_FrmPlansList.CurrentLocalBatch);
            GlobalSampling.Screenshot(data);
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            //Q_IsUploadSdxStart = true;
            //DoUploadDataToSdx();
            //Q_IsUploadSdxStart = false;
        }

        private void btnSfsj_Click(object sender, EventArgs e)
        {
            if (SamplingPLCHelper.Instance.DoWrite(276, (short)txtSfsj.Value))
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Information, $"缩分时间设定为：{txtSfsj.Value}秒");
            else
                FormHelper.RicMsgShow(txtFormLog, Untiys.Enum.MsgType.Error, $"缩分时间设定为失败");
        }
    }
}
